package client.user;

import client.common.dto.AdminPageDTO;
import client.common.result.Result;
import client.common.result.UserListResult;
import client.common.result.UserPageResult;
import client.common.result.emun.ResultCodeEnum;
import client.common.vo.UserVO;
import client.user.button.ButtonEditor;
import client.user.button.ButtonRenderer;
import remote.common.content.UserPageContent;
import remote.service.UserService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class UserArchiveQuery extends JFrame {

    private final UserService userService = new UserService() {
    }; // 实现 UserService 接口
    private JTable dataTable;
    private JTextField searchTextField;
    private JComboBox<String> searchComboBox;
    private DefaultTableModel tableModel;
    private Integer currentPage = 1;
    private Integer pageSize = 17;
    private Integer totalPages = 1;
    // Pagination controls
    private JButton firstPageButton;
    private JButton prevPageButton;
    private JButton nextPageButton;
    private JButton lastPageButton;
    private JLabel pageInfoLabel;

    public UserArchiveQuery() {
        setTitle("人员档案查询");
        setSize(1000, 600); // 设置窗口大小
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        // 设置主布局为 BorderLayout
        setLayout(new BorderLayout(10, 10));

        // 创建并添加搜索面板
        JPanel searchPanel = createSearchPanel();
        add(searchPanel, BorderLayout.NORTH);

        // 创建并添加表格面板
        JPanel tablePanel = createTablePanel();
        add(tablePanel, BorderLayout.CENTER);

        // 创建并添加分页面板
        JPanel paginationPanel = createPaginationPanel();
        add(paginationPanel, BorderLayout.SOUTH);

        // 初始刷新表格
        freshTable();

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            UserArchiveQuery userArchiveQuery = new UserArchiveQuery();
            userArchiveQuery.setVisible(true);
        });
    }

    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel searchPanel = new JPanel(new GridBagLayout());
        searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();

        // 标签
        JLabel label = new JLabel("查询方式：");
        label.setFont(new Font("Serif", Font.PLAIN, 20));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(0, 0, 0, 10);
        searchPanel.add(label, gbc);

        // 搜索 ComboBox
        searchComboBox = new JComboBox<>(new String[]{"用户名"}); // 可根据需要修改
        searchComboBox.setFont(new Font("Serif", Font.PLAIN, 15));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.2;
        searchPanel.add(searchComboBox, gbc);

        // 搜索 TextField
        searchTextField = new JTextField();
        searchTextField.setFont(new Font("Serif", Font.PLAIN, 15));
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.5;
        gbc.insets = new Insets(0, 10, 0, 10);
        searchPanel.add(searchTextField, gbc);

        // 查询按钮
        JButton searchButton = new JButton("查询");
        searchButton.setPreferredSize(new Dimension(100, 30));
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentPage = 1; // 重置为第一页
                String searchText = searchTextField.getText();
                String selectedQueryType = (String) searchComboBox.getSelectedItem();
                if ("用户名".equals(selectedQueryType)) {
                    // 进行模糊查询
                    refreshTable(searchText); // 传递搜索文本进行模糊查询
                } else if ("角色".equals(selectedQueryType)) {
                    // 根据角色进行查询
                    // 假设你已经实现了根据角色查询的逻辑
                } else {
                    // 如果未选择有效的查询类型，可以选择不执行任何操作或弹出提示
                    JOptionPane.showMessageDialog(UserArchiveQuery.this, "请选择有效的查询方式", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        gbc.gridx = 3;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        gbc.insets = new Insets(0, 10, 0, 5);
        searchPanel.add(searchButton, gbc);


        // 查询全部按钮
        JButton queryAllButton = new JButton("查询全部");
        queryAllButton.setPreferredSize(new Dimension(100, 30));
        queryAllButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentPage = 1; // 重置为第一页
                searchTextField.setText("");
                freshTable();
            }
        });
        gbc.gridx = 4;
        gbc.gridy = 0;
        gbc.insets = new Insets(0, 5, 0, 0);
        searchPanel.add(queryAllButton, gbc);

        // 添加用户按钮
        JButton addUserButton = new JButton("添加用户");
        addUserButton.setPreferredSize(new Dimension(100, 30));
        addUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 确保只传递一个 Consumer<Result> 类型的参数
                UserAddDialog userAddDialog = new UserAddDialog(result -> {
                    if (result.isSuccess()) {
                        freshTable(); // 重新刷新表格
                    } else {
                        JOptionPane.showMessageDialog(UserArchiveQuery.this, result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                });
                userAddDialog.setVisible(true);
            }
        });

        gbc.gridx = 5;
        gbc.gridy = 0;
        gbc.insets = new Insets(0, 5, 0, 0);
        searchPanel.add(addUserButton, gbc);
        // 批量导入按钮
        JButton importUserButton = new JButton("批量导入");
        importUserButton.setPreferredSize(new Dimension(100, 30));
        importUserButton.addActionListener(e -> importUsersFromExcel());
        gbc.gridx = 6; // 将导入按钮放在添加用户按钮右侧
        searchPanel.add(importUserButton, gbc);
        // 下载模板按钮
        JButton downloadTemplateButton = new JButton("下载模板");
        downloadTemplateButton.setPreferredSize(new Dimension(100, 30));
        downloadTemplateButton.addActionListener(e -> downloadTemplate());
        gbc.gridx = 7; // 将下载模板按钮放在导入按钮右侧
        searchPanel.add(downloadTemplateButton, gbc);

        return searchPanel;
    }
    private void downloadTemplate() {
        try {
            // 替换为你的资源链接
            String url = "https://for-hsxazj-halo.oss-cn-hangzhou.aliyuncs.com/template_for_user_import.xlsx";
            Desktop.getDesktop().browse(new URI(url));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "下载模板失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    private void importUsersFromExcel() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择要导入的 Excel 文件");
        fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Excel Files", "xls", "xlsx"));

        int userSelection = fileChooser.showOpenDialog(this);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToImport = fileChooser.getSelectedFile();
            Result<String> result = userService.importUserByExcel(fileToImport);
            if (result.isSuccess()) {
                JOptionPane.showMessageDialog(this, "导入成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this, result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 创建表格面板
     */
    private JPanel createTablePanel() {
        JPanel tablePanel = new JPanel(new BorderLayout());

        // 表格模型
        tableModel = new DefaultTableModel(new Object[]{"id号码", "电话号码", "身份证号", "真实姓名", "性别", "住址", "出生日期", "修改", "删除"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7 || column == 8; // 允许修改和删除列可编辑
            }
        };

        // 表格
        dataTable = new JTable(tableModel);
        dataTable.setFillsViewportHeight(true);
        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        dataTable.setFont(new Font("Serif", Font.PLAIN, 14));
        dataTable.setRowHeight(25);

        // 设置列渲染器和编辑器
        dataTable.getColumn("修改").setCellRenderer(new ButtonRenderer());
        dataTable.getColumn("修改").setCellEditor(new ButtonEditor(dataTable, true));
        dataTable.getColumn("删除").setCellRenderer(new ButtonRenderer());
        dataTable.getColumn("删除").setCellEditor(new ButtonEditor(dataTable, false));


        JScrollPane scrollPane = new JScrollPane(dataTable);
        tablePanel.add(scrollPane, BorderLayout.CENTER);

        return tablePanel;
    }

    /**
     * 创建分页面板
     */
    private JPanel createPaginationPanel() {
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));

        // 首页按钮
        firstPageButton = new JButton("首页");
        firstPageButton.addActionListener(e -> {
            if (currentPage != 1) {
                currentPage = 1;
                freshTable();
            }
        });
        paginationPanel.add(firstPageButton);

        // 上一页按钮
        prevPageButton = new JButton("上一页");
        prevPageButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                freshTable();
            }
        });
        paginationPanel.add(prevPageButton);

        // 下一页按钮
        nextPageButton = new JButton("下一页");
        nextPageButton.addActionListener(e -> {
            if (currentPage < totalPages) {
                currentPage++;
                freshTable();
            }
        });
        paginationPanel.add(nextPageButton);

        // 末页按钮
        lastPageButton = new JButton("末页");
        lastPageButton.addActionListener(e -> {
            if (currentPage != totalPages) {
                currentPage = totalPages;
                freshTable();
            }
        });
        paginationPanel.add(lastPageButton);

        // 页码信息标签
        pageInfoLabel = new JLabel("第 1 页 / 共 1 页");
        pageInfoLabel.setFont(new Font("Serif", Font.PLAIN, 14));
        paginationPanel.add(pageInfoLabel);

        return paginationPanel;
    }

    /**
     * 重新请求接口，刷新表单
     */
    public void freshTable() {
        AdminPageDTO adminPageDTO = new AdminPageDTO();
        adminPageDTO.setCurrent(currentPage.toString());
        adminPageDTO.setSize(pageSize.toString());

        // 调用远程服务获取分页数据
        UserPageResult result = userService.getUserPage(adminPageDTO);
        if (result.getCode().equals(ResultCodeEnum.NO_PERMISSION.getCode())) {
            JOptionPane.showMessageDialog(this, "权限不足，请联系管理员", "错误", JOptionPane.ERROR_MESSAGE);
            setVisible(false);
            dispose();
            return;
        } else if (result == null || result.getData() == null) {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        } else {
            setVisible(true);
        }

        // 假设返回的数据是 List<UserVO>
        List<UserVO> userList = (List<UserVO>) result.getData().getRecords(); // 需要根据实际返回类型进行转换

        // 计算总页数
        int total = result.getData().getTotal(); // 假设 result 有一个获取总数的方法
        totalPages = (int) Math.ceil((double) total / pageSize);
        if (totalPages == 0) totalPages = 1;

        // 更新页码显示
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");

        // 更新分页按钮的状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);

        // 清空当前表格数据
        tableModel.setRowCount(0);

        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 添加新数据到表格
        for (UserVO user : userList) {
            // 添加行数据
            tableModel.addRow(new Object[]{
                    user.getId(),
                    user.getPhoneNumber(),
                    user.getIdentity(),
                    user.getRealName(),
                    user.getGender(),
                    user.getAddress(),
                    dateFormat.format(new Date(String.valueOf(user.getBirth()))),
                    "修改",
                    "删除"
            });
        }
    }

    public void refreshTable(String searchText) {
        AdminPageDTO adminPageDTO = new AdminPageDTO();
        adminPageDTO.setCurrent(currentPage.toString());
        adminPageDTO.setSize(pageSize.toString());

        Object result; // 将结果声明为 Object 类型以便于处理不同的返回值

        // 如果没有输入搜索文本，则弹出提示框
        if (searchText == null || searchText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要查询的用户姓名", "提示", JOptionPane.INFORMATION_MESSAGE);
            return; // 直接返回，避免继续执行
        }

        // 如果有搜索文本，则进行模糊查询
        if (searchText != null && !searchText.isEmpty()) {
            result = userService.fuzzyQueryUserByRealName(searchText); // 模糊查询
        } else {
            // 否则正常获取分页数据
            result = userService.getUserPage(adminPageDTO);
        }

        // 处理结果
        if (result instanceof UserPageResult) {
            UserPageResult<UserPageContent> pageResult = (UserPageResult<UserPageContent>) result;
            if (pageResult.isSuccess() && pageResult.getData() != null) {
                // 更新表格数据
                updateTableWithPageResult(pageResult);
            } else {
                JOptionPane.showMessageDialog(this, pageResult.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else if (result instanceof UserListResult) {
            UserListResult listResult = (UserListResult) result;
            if (listResult.getCode() == 200) { // 假设 200 表示成功
                // 更新表格数据
                updateTableWithListResult(listResult);
            } else {
                JOptionPane.showMessageDialog(this, listResult.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 使用 UserPageResult 更新表格
    private void updateTableWithPageResult(UserPageResult<UserPageContent> pageResult) {
        UserPageContent pageContent = pageResult.getData();
        List<UserVO> userList = pageContent.getRecords(); // 假设 UserPageContent 有 getRecords() 方法
        int total = pageContent.getTotal(); // 假设 UserPageContent 有 getTotal() 方法

        // 计算总页数
        totalPages = (int) Math.ceil((double) total / pageSize);
        if (totalPages == 0) totalPages = 1;

        // 更新页码显示
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");

        // 更新分页按钮的状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);

        // 清空当前表格数据
        tableModel.setRowCount(0);

        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 添加新数据到表格
        for (UserVO user : userList) {
            tableModel.addRow(new Object[]{
                    user.getId(),
                    user.getPhoneNumber(),
                    user.getIdentity(),
                    user.getRealName(),
                    user.getGender(),
                    user.getAddress(),
                    dateFormat.format(new Date(String.valueOf(user.getBirth()))),
                    "修改",
                    "删除"
            });
        }
    }

    // 使用 UserListResult 更新表格
    private void updateTableWithListResult(UserListResult listResult) {
        List<UserVO> userList = listResult.getData(); // 获取用户列表

        // 清空当前表格数据
        tableModel.setRowCount(0);

        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 添加新数据到表格
        for (UserVO user : userList) {
            tableModel.addRow(new Object[]{
                    user.getId(),
                    user.getPhoneNumber(),
                    user.getIdentity(),
                    user.getRealName(),
                    user.getGender(),
                    user.getAddress(),
                    dateFormat.format(new Date(String.valueOf(user.getBirth()))),
                    "修改",
                    "删除"
            });
        }
    }
}